/*
 * @Description: 测肤报告
 * @Author: kanglin
 * @Date: 2018-09-11 14:56:14
 * @Copyright: Created by Panxsoft.
 */
import API_LIST from 'src/API_LIST';
import axios from 'axios';
import Toast from 'cube-ui/lib/toast';

const state = {
	touch: {
		options: [],
		active_option: {},
		product_groups: [],
	},
	image: {
		options: [],
		active_option: {},
		product_groups: [],
	},
	product_groups_params: {

	},
	product_groups_cache: {

	},
};

const getters = {
	getImageOptions(state) {// eslint-disable-line
		return state.image.options;
	},
	getImageActiveOption(state) {// eslint-disable-line
		return state.image.active_option;
	},
	getImageProductGroups(state) {// eslint-disable-line
		return state.image.product_groups;
	},

    getTouchOptions(state) {// eslint-disable-line
		return state.touch.options;
	},
	getTouchActiveOption(state) {// eslint-disable-line
		return state.touch.active_option;
	},
    getTouchProductGroups(state) {// eslint-disable-line
		return state.touch.product_groups;
	},
};

const mutations = {
	saveOptions(state, {type ,options}) { // eslint-disable-line
		// Object.assign(state[type].options, options);
		state[type].options = options;
	},
  saveActiveOption(state, {type, active_option}) {// eslint-disable-line
		// Object.assign();
		state[type].active_option = active_option;
	},
	saveGeneratedProductGroups(state, {type, product_groups}) {// eslint-disable-line
		state[type].product_groups = Object.assign([], product_groups);
	},
};

function fetchData(url, params) {
	return axios.get(url, { params })
		.then(({ data }) => {
			if (data.code !== 0) {
				throw new Error(data.error);
			} else {
				return data.group_recommend_products;
			}
		});
}

const actions = {
	/**
	 *  获取推荐商品
	 */
	fetchRecommendProductGroup(context, params) {
		const { type_skin_record_id } = params;
		if (type_skin_record_id in context.state.product_groups_cache) { // 读取缓存
			return context.state.product_groups_cache[type_skin_record_id];
		}
		const query = Object.assign({}, context.state.product_groups_params, params);
		context.state.product_groups_params = query;
		return fetchData(API_LIST.INDEX_GROUP_BY_CATEGORY_ID, query)
			.then((result) => {
				context.state.product_groups_cache[type_skin_record_id] = result;
				return result;
			})
			.catch((error) => {
				const toast = Toast.$create({
					type: 'error',
					time: 2000,
					txt: error.message || error.statusText,
				});
				toast.show();
			});
	},
};

export default {
	namespaced: true,
	state,
	getters,
	mutations,
	actions,
};
